<?php 
require_once BASE_PATH.'application/models/basedao'.EXT;

class articuloDAO extends baseDAO {
	
    var $table = 'articulos';
    var $id    = 'articulo_k';
    var $default = 1;
    
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function _defaultSQL($default = 1) {

	$this->default = $default!=1 ? $default : $this->default;
	
	if($this->default)
		$this->db->where('tipo','articulos');
	
        $this->db->where($this->table.".activo", 1);
	
    }
    
    function _findByTags($tags, $data = array()) {
	
	$this->load->model("sphinxdao");
	
	if(isset($data["limit"]))
	    $this->sphinxdao->SetLimits(intval($data["limit"][0]),intval($data["limit"][1]));
	
	if(isset($data["filter"])){
		
		if(!isset($data["filter"][2]))
			$data["filter"][2] = TRUE;
		
		
		$this->sphinxdao->SetFilter($data["filter"][0],array($data["filter"][1]),$data["filter"][2]);
	}
	
	if(isset($data["filter2"])){
		
		if(!isset($data["filter2"][2]))
			$data["filter2"][2] = TRUE;
		
		
		$this->sphinxdao->SetFilter($data["filter2"][0],array($data["filter2"][1]),$data["filter2"][2]);
	}
	
        $this->sphinxdao->setTables(array("articulos"));
	$this->sphinxdao->SetSortMode(SPH_SORT_EXTENDED,"@relevance DESC, fecha_evento_stamp DESC,fecha_creacion_stamp DESC");
	
	if(is_numeric($tags))
	    $records = $this->sphinxdao->select("@(id) ".$tags,true);
	else{
	    
	    $this->sphinxdao->SetMatchMode("SPH_MATCH_EXTENDED2"); 
	    $records = $this->sphinxdao->select("@(titulo,etiquetas) ".$tags."*",true);
	}
        return $records;
	
	//return $this->findByMatchColumn("etiquetas",$tags,$data);
    }
    
    function findByTags($tags, $data = array()) {
	
	return $this->findByMatchColumn("etiquetas",$tags,$data);
    }
    
    function getMasVistos($limit = 2, $data = array()) {

        $data = array_merge($data, array(
            "limit" => array(0, $limit),
            "order" => array("fecha_visita", "ASC")
                ));

        return $this->_select($data);
    }
    
    function getMasCompartido($limit = 2, $data = array()) {

        $data = array_merge($data, array(
            "limit" => array(0, $limit),
            "order" => array("fecha_compartido", "ASC")
                ));

        return $this->_select($data);
    }
    
    function getUltimos($limit = 2, $data = array()) {

        $data = array_merge($data, array(
            "limit" => array(0, $limit),
            "order" => array("fecha_creacion", "DESC")
                ));

        return $this->_select($data);
    }
    
    function setVisita($id){
	$this->db->set('visitas', 'visitas+1', FALSE);
        $this->db->set('fecha_visita', 'NOW()', FALSE);

        $this->db->where($this->id, $id);
        $this->db->update($this->table);
    }

    
    function findByStatus($value){
        return $this->findByColumn("status",$value);
    }
    
    function getCategories($data = array())
    {
	$this->load->model("categoriadao");
	return $this->categoriadao->findByTabla($this->table,$data);
    }
	function _getTwitter($url) {

        $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
        $json = json_decode($json_string, true);

        return intval($json['count']);
    }

    function _getFacebook($url) {

        $json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
        $json = json_decode($json_string, true);

        return @intval($json[$url]['shares']);
    }

    function _getGoogle($url) {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        $curl_results = curl_exec($curl);
        curl_close($curl);

        $json = json_decode($curl_results, true);

        return intval($json[0]['result']['metadata']['globalCounts']['count']);
    }
	
    function getTotalCompartido(){
	    
	$sFacebook = $this->_getFacebook(current_url());
	$sTwiter = $this->_getTwitter(current_url());
	$sGoogle = $this->_getGoogle(current_url());
	
	return ($sFacebook + $sTwiter + $sGoogle);
    }
	
    function setCompartido($id) {

	$shares = $this->getTotalCompartido();
	
	if($shares > 0){
	    $records = $this->_findById($id);

	    if($shares > $records->compartidos)
	    {
		$this->db->set('compartidos', $shares);
		$this->db->set('fecha_compartido', 'NOW()', FALSE);

		$this->db->where($this->id, $id);
		$this->db->update($this->table);
	    }

	}
    }
}
?>